{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "626d929f",
   "metadata": {},
   "source": [
    "### 5.拟合多项式函数\n",
    "\n",
    "假设我们预测一个导弹的飞行轨迹，按照物理学可以得知他的模型为：\n",
    "\n",
    "$$\n",
    "y = at^2 + bt + c\n",
    "$$\n",
    "\n",
    "那么显然我们需要求解三个参数$a,b,c$，类似地我们可以定义损失函数：\n",
    "\n",
    "$$\n",
    "L = \\sum_{i=1}^N (y_i - at_i^2 - bt_i - c)^2\n",
    "$$\n",
    "\n",
    "获取更新项\n",
    "\n",
    "$$\n",
    "L = \\sum_{i=1}^N (y_i - at_i^2 - bt_i - c)^2\n",
    "$$\n",
    "\n",
    "\\begin{eqnarray}\n",
    "\\frac{\\partial L}{\\partial a} & = & - 2\\sum_{i=1}^N (y_i - at_i^2 - bt_i -c) t_i^2 \\\\\n",
    "\\frac{\\partial L}{\\partial b} & = & - 2\\sum_{i=1}^N (y_i - at_i^2 - bt_i -c) t_i \\\\\n",
    "\\frac{\\partial L}{\\partial c} & = & - 2\\sum_{i=1}^N (y_i - at_i^2 - bt_i -c)\n",
    "\\end{eqnarray}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "48e7d6a1",
   "metadata": {},
   "source": [
    "**在这里我们仅列出使用sklearn实现的方法**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "deaf9491",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([800.,  90., -20.])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Fitting polynomial functions\n",
    "import numpy as np\n",
    "from sklearn.preprocessing import PolynomialFeatures\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.pipeline import Pipeline#引入流水线（frequently used）\n",
    "\n",
    "t = np.array([2, 4, 6, 8])\n",
    "\n",
    "pa = -20\n",
    "pb = 90\n",
    "pc = 800\n",
    "\n",
    "y = pa*t**2 + pb*t + pc\n",
    "\n",
    "model = Pipeline([('poly', PolynomialFeatures(degree=2)),\n",
    "                  ('linear', LinearRegression(fit_intercept=False))])\n",
    "model = model.fit(t[:, np.newaxis], y)\n",
    "model.named_steps['linear'].coef_\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
